﻿/*
 * 科室
 *
*/
var Technology = function (schedule, options) {
    var finishList = [],
        unFinishList = [],
        scheduleType = 0,
        scheduleExamRequest = null;
    //页面初始化
    this.init = function (eventInit) {
        var searchBarH = $('#searchBar');
        if (searchBarH.length) {
            $('#techMainContain').height($(window).height() - 100 - searchBarH.height() - 60);
            $('.technology_container').height($(window).height() - 100 - searchBarH.height() - 60);
            $('.technology_list_container').height($(window).height() - 450 - $('.technology_right_first').height()-20);
        } else {
            $('#techMainContain').height($(window).height() - 100);
            $('.technology_container').height($(window).height() - 100);
            $('.technology_list_container').height($(window).height() - 260 - $('.technology_right_first').height());
        }
       

        if (!schedule) {
            schedule = new Schedule("Technology", $('#hdnRelativeUrl').val());
            schedule.days = 7;
        }

        schedule.getExamRequestScheduleInfoList(getExamRequestListCallback);

        finishList.current = 0;
        unFinishList.current = 0;

        if (!eventInit)
            pageEventInit();
    };

    this.clear = function () {
        $('.finish-container').html("");
        $('.un-finish-container').html("");
        $('.unbooknum').text('');
        $('.booknum').text('');
        $('.name').text("");
        $('.sex').text("");
        $('.age').text("")
        $('.department').text("");
        finishList = [];
        unFinishList = [];
    };

    //获取申请单列表+1
    var getExamRequestListCallback = function (data) {
        $('.technology_container .finish-container').html("");
        $('.technology_container .un-finish-container').html("");

        $('.name').text(data[0].Name);
        $('.sex').text(data[0].Sex);
        $('.age').text(data[0].Age + data[0].AgeUnit);

        $('.clinicDiagnosis').text(data[0].ClinicDiagnosis);
        $('.relevantClinicalInfo').text(data[0].RelevantClinicalInfo);
        $('.requestDeptName').text(data[0].RequestDeptName);
        $('.providerName').text(data[0].ProviderName);

        for (var i = 0; i < data.length; i++) {
            if (data[i].ScheduleFlag) {
                finishList.push(data[i]);
                bindFinish(data[i]);
            } else {
                unFinishList.push(data[i]);
                bindUnFinish(data[i]);
            }
        }
        $('#print .print_num').text(finishList.length);
        $('.booknum').text('（' + finishList.length + '）');
        $('.unbooknum').text('（' + unFinishList.length + '）');
    };

    //未预约+1
    var bindUnFinish = function (exam) {
        var date = !exam.ScheduleStartDate ? "" : exam.ScheduleStartDate.substr(0, 10);
        var time = (!exam.ScheduleStartDate || !exam.ScheduleEndDate) ? "" : exam.ScheduleStartDate.substr(11, 5) + "-" + exam.ScheduleEndDate.substr(11, 5);
        var temp = '<div id="' + exam.PlacerOrderNO + '" class="isFinsh_items ifbook_items" data-placerorderno=' + exam.PlacerOrderNO + '>' +
                    ' <div class="isFinsh_time ">' +
                        '<span class="check_click" style="margin-top:2px;">' + exam.ServiceSectID + '</span>' +
                        '<span class="check_click" style="padding-left:10px;">' + exam.ProcedureName + '</span>' +
                    ' </div>' +
                    '<div class="isfinish_detail isfinshied_datetime">预约日期：' +
                        '<span>' + date + '</span>' +
                    ' </div>' +
                    '<div class="isfinish_detail isfinshied_time">预约时间：' +
                        '<span>' + time + '</span>' +
                    ' </div>' +
                    '<div class="isfinish_detail isfinshied_add">预约资源：' +
                        '<span>' + exam.ScheduleResourceName + '</span>' +
                    '</div>' +
                ' </div>';

        $('.un-finish-container').append(temp);
        var searchBarH = $('#searchBar');
        if (searchBarH.length) {
            $('.un-finish-container').css({ 'max-height': ($(window).height() - 420) / 2 });
        } else {
            $('.un-finish-container').css({ 'max-height': ($(window).height() - 320) / 2 });
        }
       
    };

    //已预约+1
    var bindFinish = function (exam) {
        var date = !exam.ScheduleStartDate ? "" : exam.ScheduleStartDate.substr(0, 10);
        var time = (!exam.ScheduleStartDate || !exam.ScheduleEndDate) ? "" : exam.ScheduleStartDate.substr(11, 5) + "-" + exam.ScheduleEndDate.substr(11, 5);
        var temp = '<div id="' + exam.PlacerOrderNO + '" class="isFinsh_items ifbook_items" data-placerorderno=' + exam.PlacerOrderNO + '>' +
                    ' <div class="isFinsh_time">' +
                        '<input type="checkbox" name="check" class="check checked_bg" data-placerorderno="' + exam.PlacerOrderNO + '" checked>' +
                        '<span class="check_click" style="margin-top:2px;">' + exam.ServiceSectID + '</span>' +
                        '<span class="check_click" style="padding-left:10px;">' + exam.ProcedureName + '</span>' +
                        '<span class="cancel_book">取消</span>' +
                    ' </div>' +
                   '<div class="isfinish_detail isfinshied_datetime">预约日期：' +
                        '<span>' + date + '</span>' +
                    ' </div>' +
                    '<div class="isfinish_detail isfinshied_time">预约时间：' +
                        '<span>' +time + '</span>' +
                    ' </div>' +
                    '<div class="isfinish_detail isfinshied_add">预约资源：' +
                        '<span>' + exam.ScheduleResourceName + '</span>' +
                    '</div>' +
                ' </div>';

        $('.technology_container .finish-container').append(temp);
        var searchBarH = $('#searchBar');
        if (searchBarH.length) {
            $('.finish-container').height(($(window).height() - $('#unFinishContainer').height() - 280) - searchBarH.height()-40);
        } else {
            $('.finish-container').height(($(window).height() - $('#unFinishContainer').height() - 280));
        }
        
    };

    var pageEventInit = function () {
        //取消预约
        $('.technology_container').on('click', '.cancel_book', cancelSchedule);

        //修改预约时间
        $('.finish-container').on('click', '.isfinish_detail', editSchedule);

        //未预约开始预约
        $('.technology_container').on('click', '.isFinsh_items', startSchedule);

        //保存预约
        $('#save_time').on('click', saveExamSchedule);

        //切换星期
        $('.technology_list_container').on('click', '.day_items', changeWeekDay);

        //切换资源
        $('.technology_list_container').on('click', '.chose_palce', changeResource);

        //选中时间
        $('.technology_list_container').on('click', '.schedule-time', selectTime);

        //打印
        $('#print').on('click', print);

        //时间修改
        layui.use('laydate', function () {
            var laydate = layui.laydate;
            var start = {
                min: laydate.now()
                  , max: '2099-06-16 23:59:59'
                  , istoday: false
                  , choose: function (datas) {
                      schedule.startDate = datas;

                      var relateExamRequestList = [];

                      $.each(schedule.examRequestList, function (i, n) {
                          if (n.PlacerOrderNO != scheduleExamRequest.PlacerOrderNO) {
                              if (n.ScheduleStartDate && n.ScheduleEndDate) {
                                  relateExamRequestList.push(n);
                              }
                          }
                      });

                      schedule.getScheduleInfo(scheduleExamRequest, relateExamRequestList, '', '', getScheduleInfoCallback);
                  }
            };
            document.getElementById('date').onclick = function () {
                start.elem = this;
                laydate(start);
            }
        });

        //选中某一条数据
        $(".technology_left").on('click', '.check', function (ev) {
            var ev = ev || event;
            ev.stopPropagation();

            var $this = $(this).closest('.isFinsh_time').find('.check');
            var isChecked = $this.prop('checked');
            var print_num = Number($('#print .print_num').text());
            if (isChecked) {
                $('#print .print_num').text(print_num + 1);
                $this.addClass('checked_bg');
            } else {
                if (print_num >= 1) { $('#print .print_num').text(print_num - 1); } else { $('#print .print_num').text(0); }
                $this.removeClass('checked_bg');
            }
            if ($('#print .print_num').text() == 0) { $('#print').addClass("btn_no_print"); } else { $('#print').removeClass("btn_no_print") }
        });

        //全选
        $(".technology_left").on('click', '.check_all', function () {
            var $this = $(this);
            var isChecked = $this.prop('checked');
            var print_num = Number($('#print .print_num').text());
            var checkArr = $('.check');
            if (isChecked) {
                $this.addClass('checked_bg');
                $.each(checkArr, function (i, v) {
                    checkArr.eq(i).prop("checked", true);
                    checkArr.eq(i).addClass('checked_bg');

                })
                $('#print').removeClass("btn_no_print");
                $('#print .print_num').text(finishList.length);
            } else {
                $this.removeClass('checked_bg');
                $.each(checkArr, function (i, v) {
                    checkArr.eq(i).prop("checked", false);
                    checkArr.eq(i).removeClass('checked_bg');
                });
                $('#print').addClass("btn_no_print");
                $('#print .print_num').text('0');
            }
        });
    };

    //打印
    var print = function () {
        var printArr = [];
        var checkArr = $('.finish-container .checked_bg');

        $.each(checkArr, function (i, n) {
            var placerorderno = $(n).data('placerorderno');
            printArr.push({ PlacerOrderNO: placerorderno });
        });

        var printNum = printArr.length;
        $.each(printArr, function (i, n) {
            setTimeout(function () {
                schedule.print(n);
            }, 2000);
        });

        if (printNum == 0) {
            schedule.alert('请选择要打印的预约!');
        }
    };

    //取消预约+2
    var cancelSchedule = function (ev) {
        var ev = ev || event;
        ev.stopPropagation();

        var $this = $(this);

        schedule.comfirm('是否确定取消预约？', function () {
            var placerOrderNO = $this.closest('.ifbook_items').data("placerorderno");

            $.each(finishList, function (i, n) {
                if (n.PlacerOrderNO == placerOrderNO) {
                    schedule.cancelSchedule({
                        'PlacerOrderNO': placerOrderNO
                    }, function (data) {
                        n.ScheduleResourceID = '';
                        n.ScheduleResourceName = '';
                        n.ScheduleStartDate = '';
                        n.ScheduleEndDate = '';
                        n.ScheduleStatus = 1;
                        n.ScheduleFlag = false;

                        finishList.splice(i, 1);
                        $('#' + placerOrderNO).remove();

                        unFinishList.push(n);
                        bindUnFinish(n);

                        $('.booknum').text('（' + finishList.length + '）');
                        $('.unbooknum').text('（' + unFinishList.length + '）');
                    });

                    return false;
                }
            });
        });
    };

    //修改预约时
    var editSchedule = function () {
        scheduleType = 1;

        var ifbook_itemsarr = $('.ifbook_items');
        $.each(ifbook_itemsarr, function (i) {
            ifbook_itemsarr.eq(i).removeClass('isFinsh_items_active');
        })

        $(this).closest('.ifbook_items').addClass('isFinsh_items_active');
        var placerOrderNO = $(this).closest('.ifbook_items').data('placerorderno');

        var relateExamRequestList = [];
        $.each(schedule.examRequestList, function (i, n) {
            if (n.PlacerOrderNO == placerOrderNO) {
                scheduleExamRequest = n;
            } else {
                if (n.ScheduleStartDate && n.ScheduleEndDate) {
                    relateExamRequestList.push(n);
                }
            }
        });

        schedule.getScheduleInfo(scheduleExamRequest, relateExamRequestList, '', "", getScheduleInfoCallback);

        $('.ServiceSectID').text(scheduleExamRequest.ServiceSectID);
        $('.ProcedureName').text(scheduleExamRequest.ProcedureName);

        $('.technology_right_sed').show();
    };

    //开始预约
    var startSchedule = function () {
        scheduleType = 0;

        var ifbook_itemsarr = $('.ifbook_items');
        $.each(ifbook_itemsarr, function (i) {
            ifbook_itemsarr.eq(i).removeClass('isFinsh_items_active');
        });
        $(this).closest('.ifbook_items').addClass('isFinsh_items_active');
        var placerOrderNO = $(this).closest('.ifbook_items').data('placerorderno');

        var relateExamRequestList = [];
        $.each(schedule.examRequestList, function (i, n) {
            if (n.PlacerOrderNO == placerOrderNO) {
                scheduleExamRequest = n;
            } else {
                if (n.ScheduleStartDate && n.ScheduleEndDate) {
                    relateExamRequestList.push(n);
                }
            }
        });

        schedule.getScheduleInfo(scheduleExamRequest, relateExamRequestList, '', "", getScheduleInfoCallback);

        $('.ServiceSectID').text(scheduleExamRequest.ServiceSectID);
        $('.ProcedureName').text(scheduleExamRequest.ProcedureName);

        $('.technology_right_sed').show();
    };

    //确认预约
    var saveExamSchedule = function () {
        schedule.saveExamSchedule(null, function (data) {
            $.each(data, function (i, n) {
                $.each(schedule.examRequestList, function (j, m) {
                    if (n.PlacerOrderNO == m.PlacerOrderNO) {
                        if (n.ScheduleFlag) {
                            n.ChangeFlag = false;
                            $.each(unFinishList, function (k, l) {
                                if (n.PlacerOrderNO == l.PlacerOrderNO) {
                                    unFinishList.splice(k, 1);
                                    $('#' + l.PlacerOrderNO).remove();
                                    return false;
                                }
                            });

                            finishList.push(m);
                            bindFinish(m);
                        } else {
                            n.ScheduleStatus = 0;
                            n.ScheduleFlag = true;
                            n.ChangeFlag = false;
                        }

                        return false;
                    }
                });
            });
           
            $('.booknum').text('（' + finishList.length + '）');
            $('.unbooknum').text('（' + unFinishList.length + '）');
        });
    };

    //获取单个申请的预约资源排班+1
    var getScheduleInfoCallback = function (data) {
        scheduleExamRequest.ScheduleResourceUID = data.ResourceUID;
        scheduleExamRequest.ScheduleResourceName = data.ResourceName;
        scheduleExamRequest.ScheduleStartDate = data.ScheduleDate + data.ScheduleTime.split('-')[0];
        scheduleExamRequest.ScheduleEndDate = data.ScheduleDate + data.ScheduleTime.split('-')[1];
        scheduleExamRequest.Quantity = data.Quantity;
        scheduleExamRequest.scheduleArrangeList = [];
        var resourceTitleHtml = "",
            resourceContentHtml = "",
            scheduleArrangeDateInfoList = [];

        $.each(data.ScheduleArrangeResourceInfoList, function (i, n) {
            if (n.ResourceUID == data.ResourceUID) {
                scheduleExamRequest.ObservationLocation = n.ResourceLocation;
                scheduleArrangeDateInfoList = n.ScheduleArrangeDateInfoList;

                resourceTitleHtml = '<li class="border_right_none chose_palce layui-this" data-resourceuid="' + n.ResourceUID +
                                        '" data-resourceLocation="' + n.ResourceLocation + '"' +
                                    '">' + n.ResourceName + '</li>' + resourceTitleHtml;
                resourceContentHtml = '<div class="layui-tab-item layui-show time-detail">' +
                                            '<div class="technology_week"></div>' +
                                            '<table class="technology_table " border="0" cellspacing="1" cellpadding="0"></table>' +
                                        '</div>' + resourceContentHtml;
            } else {
                var border_right_none = (i == data.ScheduleArrangeResourceInfoList - 1) ? "" : "border_right_none";
                resourceTitleHtml += '<li class="' + border_right_none + ' chose_palce" data-resourceuid="' + n.ResourceUID +
                                        '" data-resourceLocation="' + n.ResourceLocation + '"' +
                                     '">' + n.ResourceName + '</li>';
                resourceContentHtml += '<div class="layui-tab-item time-detail">' +
                                            '<div class="technology_week"></div>' +
                                            '<table class="technology_table " border="0" cellspacing="1" cellpadding="0"></table>' +
                                        '</div>';
            }
        });

        $('.layui-tab-title').html(resourceTitleHtml);
        $('.layui-tab-content').html(resourceContentHtml);
        $('#date').val(data.ScheduleDate); //推荐日期
        addResourceArrange(scheduleArrangeDateInfoList);
    };

    //添加日期下的时间组+2
    var addResourceArrange = function (scheduleArrangeDateInfoList) {
        var weekHtml = "";

        $.each(scheduleArrangeDateInfoList, function (i, n) {
            var arrangeDay = imcis.convertDateFromJson(n.ArrangeDay, true);
            var arrangeWeek = '';
            switch (n.ArrangeWeek) {
                case 7:
                    arrangeWeek = "周日";
                    break;
                case 1:
                    arrangeWeek = "周一";
                    break;
                case 2:
                    arrangeWeek = "周二";
                    break;
                case 3:
                    arrangeWeek = "周三";
                    break;
                case 4:
                    arrangeWeek = "周四";
                    break;
                case 5:
                    arrangeWeek = "周五";
                    break;
                case 6:
                    arrangeWeek = "周六";
                    break;
            }
            weekHtml += '<div class="day_' + i + ' day_items" data-i="' + i + '">' +
                            '<p class="myd">' + arrangeDay + '</p>' +
                            '<p class="week">' + arrangeWeek + '</p>' +
                        '</div>';

            scheduleExamRequest.scheduleArrangeList[i] = n.ScheduleArrangeTimeInfoList;
        });

        $('.layui-show .technology_week').html(weekHtml);
        $('.layui-show .technology_week .day_0').addClass('actived_item').addClass('active_week');

        addArrangeTime(scheduleExamRequest.scheduleArrangeList[0]);
    };

    //时间组添加时间段+2
    var addArrangeTime = function (timeList) {
        var totalStr = '';
        var addTdStr = '';

        if (timeList.length % 8 != 0) {
            var i = 8 - ((timeList.length) % 8);
            for (var j = 0; j < i; j++) {
                addTdStr += '<td class="schedule-banlk " style=" width: 12.5%;"></td>'
            }
            addTdStr += '</tr>';
        }

        for (var i = 0; i < timeList.length; i++) {
            var temp = '';
            var time = timeList[i].StartTime + "-" + timeList[i].EndTime;
            var title = timeList[i].TitleMsg || "";
            switch (timeList[i].ScheduleTimeStatus) {
                case 3:
                case 4:
                    //不可预约时间           
                    temp += '<td class="schedule-time schedule-disable" ';
                    break;
                case 0: //选中的时间
                    temp += '<td class="schedule-time schedule-current" ';
                    break;
                case 1:
                    //选中的时间
                    temp += '<td class="schedule-time schedule-finish" ';
                    break;
                default:
                    //可预约时间
                    temp += '<td class="schedule-time schedule-enable" ';
                    break;
            }

            temp += 'data-uid="' + timeList[i].TimeDetailUID + '" data-quantity="' + timeList[i].Quantity + '" title="' + title + '"><span>' + time +
                        '</span><br><span>' + timeList[i].AppointmentQuantity + '/' + timeList[i].Quantity + '</span></td>';

            if (i == 0 || i % 8 == 0) {
                totalStr = totalStr + '<tr>' + temp;
            } else if ((i + 1) % 8 == 0) {
                totalStr = totalStr + temp + '</tr>'
                temp = '';
            } else {
                totalStr = totalStr + temp;
            }
        }

        $('.layui-show .technology_table').html(totalStr + addTdStr);
    };

    //选中时间+1
    var selectTime = function () {
        if ($(this).hasClass('schedule-disable')) {
            return;
        } else if ($(this).hasClass('schedule-enable')) {
            $('.technology_list_container .schedule-current').removeClass('schedule-current').addClass('schedule-enable');
            $(this).addClass('schedule-current');

        } else if ($(this).hasClass('schedule-finish')) {
            $('.technology_list_container .schedule-current').removeClass('schedule-current');
        }

        var $resource = $('.chose_palce.layui-this');
        scheduleExamRequest.ScheduleResourceUID = $resource.data('resourceuid');
        scheduleExamRequest.ScheduleResourceName = $resource.text();
        scheduleExamRequest.ObservationLocation = $resource.data('resourcelocation');

        var scheduleDate = $('.time-detail.layui-show .technology_week .active_week .myd').text();
        var scheduleTime = $($(this).find('span')[0]).text();
        scheduleExamRequest.ScheduleStartDate = scheduleDate + " " + scheduleTime.split('-')[0];
        scheduleExamRequest.ScheduleEndDate = scheduleDate + " " + scheduleTime.split('-')[1];
        scheduleExamRequest.Quantity = $(this).data('quantity');

        if (scheduleExamRequest.ScheduleFlag) {
            if (scheduleExamRequest.ScheduleResourceName == scheduleExamRequest.OriginalScheduleResourceName &&
                        scheduleExamRequest.ScheduleStartDate == scheduleExamRequest.OriginalScheduleStartDate &&
                        scheduleExamRequest.ScheduleEndDate == scheduleExamRequest.OriginalScheduleEndDate) {
                scheduleExamRequest.ChangeFlag = false;
            } else {
                scheduleExamRequest.ChangeFlag = true;
            }
        }

        var items = $('.isFinsh_items_active .isfinish_detail span');
        $(items[0]).text(scheduleDate);
        $(items[1]).text(scheduleTime);
        $(items[2]).text($resource.text());
    };

    var changeWeekDay = function () {
        $('.layui-show .technology_week .active_week').removeClass('actived_item').removeClass('active_week');
        $(this).addClass('actived_item').addClass('active_week');

        var i = parseInt($(this).data('i'));
        addArrangeTime(scheduleExamRequest.scheduleArrangeList[i]);
    }

    var changeResource = function () {
        var resourceUID = $(this).data('resourceuid');
        var relateExamRequestList = [];

        $.each(schedule.examRequestList, function (i, n) {
            if (n.PlacerOrderNO != scheduleExamRequest.PlacerOrderNO) {
                if (n.ScheduleStartDate && n.ScheduleEndDate) {
                    relateExamRequestList.push(n);
                }
            }
        });

        schedule.getScheduleInfo(scheduleExamRequest, relateExamRequestList, resourceUID, "", function (data) {
            if (data.ScheduleArrangeResourceInfoList.length > 0) {
                var resourceInfo = data.ScheduleArrangeResourceInfoList[0];
                addResourceArrange(resourceInfo.ScheduleArrangeDateInfoList);
            }
        });
    };

    //切换日期
    var changeDate = function () {
        var loading = layer.load(1, { shade: [0.4, '#333'] }); //加载层
        var day_itemsArr = $('.technology_week .day_items');
        $.each(day_itemsArr, function (i) {
            day_itemsArr.eq(i).removeClass('active_week');
        })
        var $this = $(this).addClass('active_week');
        dateIndex = $(this).data("i");
        var date = $this.find('.myd').text();
        currentRecommend.scheduleDate = date;
        var scheduleArrange = currentRecommend.ScheduleArrangeList[dateIndex];
        var now = new Date();
        var isGroupName = false;
        if (date == now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate()) {
            now = new Date(date + " " + now.getHours() + ":" + now.getMinutes());
            for (var i = 0; i < scheduleArrange.groupList.length; i++) {
                var times = scheduleArrange[scheduleArrange.groupList[i]].times;

                for (var j = 0; j < times.length; j++) {
                    var start = new Date(date + " " + times[j].StartTime);
                    var end = new Date(date + " " + times[j].EndTime);

                    if (now >= start && now <= end) {
                        scheduleArrange.scheduleGroupName = times[j].GroupName;
                        isGroupName = true;
                        break;
                    }
                }

                if (isGroupName) {
                    break;
                }
            }
        }
        if (!isGroupName) {
            scheduleArrange.scheduleGroupName = scheduleArrange.groupList[0];
        }
        var placerOrderNO = scheduleExamRequest.PlacerOrderNO;
        addDateGroup(scheduleArrange);
        layer.close(loading);
    };
};